﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;

namespace MyPrismDemo.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IContainerProvider _containerProvider; // 注入 IContainerProvider
        private IRegion _region;
        private readonly Dictionary<string, object> _viewCache = new Dictionary<string, object>(); // 用于缓存视图实例

        public DelegateCommand<string> ShowViewCommand { get; }
        public DelegateCommand<string> ShowAViewCommand { get; }
        public MainWindowViewModel(IRegionManager regionManager, IContainerProvider containerProvider)
        {
            _regionManager = regionManager;
            _containerProvider = containerProvider;

            // 初始化导航命令
            ShowViewCommand = new DelegateCommand<string>(ActivateView);
            ShowAViewCommand = new DelegateCommand<string>(ActivateAView);
        }

        // 初始化区域方法，提前加载视图并缓存
        public void InitializeRegion()
        {
            if (_regionManager.Regions.ContainsRegionWithName("MainRegion"))
            {
                _region = _regionManager.Regions["MainRegion"];

                // 提前解析视图并缓存
                AddViewToCache("ViewA");
                AddViewToCache("ViewB");
                AddViewToCache("ViewC");

                
            }
            else
            {
                throw new Exception("MainRegion 未注册！");
            }
        }

        private void AddViewToCache(string viewName)
        {
            // 检查是否已经解析过该视图，如果没有则解析并缓存
            if (!_viewCache.ContainsKey(viewName))
            {
                var view = _containerProvider.Resolve<object>(viewName);
                _viewCache[viewName] = view;
            }
        }

        private void ActivateAView(string viewName)
        {
            ActivateView("ViewA");
            var aRegion = _regionManager.Regions["aRegion"];
            if (aRegion == null) return;
            var view = aRegion.GetView(viewName);
            aRegion.Activate(view);

        }

        private void ActivateView(string viewName)
        {
            if (_region == null) return;

            // 检查视图是否已经解析并缓存
            if (_viewCache.ContainsKey(viewName))
            {

                var view = _viewCache[viewName];
                if (_region.GetView(viewName) == null) _region.Add(view, viewName);
                _region.Activate(view);
            }
            else
            {
                throw new Exception($"视图 {viewName} 未找到！");
            }
        }
    }
}
